import { defineStore } from 'pinia'
import { TokenInfo, UserInfo } from '@/plugins/store/interface'
import { userAuthInfo } from '@/api/common'

export const user = defineStore('user', {
  state: (): UserInfo => {
    return {
      username: '',
      avatar: '',
      roles: [],
    }
  },
  actions: {
    dataFill(state: UserInfo) {
      this.$state = state
    },
    getUserInfo() {
      return this.$state
    },
    getRoles() {
      return this.$state.roles
    },
    async setUserInfo() {
      const res = await userAuthInfo()
      this.$state = res.data
    },
  },
})

export const auth = defineStore('authToken', {
  state: (): TokenInfo => {
    return {
      token: '',
    }
  },
  actions: {
    dataFill(state: TokenInfo) {
      this.$state = state
    },
    getToken() {
      return this.$state.token
    },
    logout() {
      this.$state.token = ''
      location.reload()
    },
  },
  persist: true,
})

export const permission = defineStore('permission', {
  state: (): any[] => {
    return [
      {
        children: [],
        meta: undefined,
        path: '',
      },
    ]
  },
  actions: {
    dataFill(state: any[], roles: string[]) {
      this.$state = filterPermissionsRouters(state, roles)
    },
    getPermissions() {
      return this.$state
    },
  },
})

function filterPermissionsRouters(routes: any[], roles: string[]): any[] {
  let res: any[] = []
  routes.forEach((route) => {
    const roleCode = route.meta?.roleCode || route.title
    if (roles.indexOf(roleCode) !== -1) {
      if (route.children) {
        res = [...route.children, ...res]
      }
    }
  })
  return res
}
